package com.study.util;

import com.alibaba.fastjson.JSON;
import com.study.constant.CommonConstant;
import com.study.vo.LoginUserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import sun.misc.BASE64Decoder;

import javax.security.auth.login.Configuration;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;

/**
 * jwt token 解析工具类
 */
public class TokenParseUtil {

    public static LoginUserInfo parseUserInfoFromToken(String token) throws Exception{
        if(null == token){
            return null;
        }

        Jws<Claims> claimsJws = parseToken(token,getPublicKey());

        Claims body = claimsJws.getBody();

        //如果 token过期 返回null
        if(body.getExpiration().before(new Date())){
            return null;
        }

        return JSON.parseObject(body.get(CommonConstant.JWT_USER_INFO_KEY).toString(),
                LoginUserInfo.class
                );
    }

    /**
     * 通过公钥去解析 JWT Token
     * @param token
     * @param publicKey
     * @return
     */
    private static Jws<Claims> parseToken(String token,PublicKey publicKey){
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }

    /**
     * 根据本地存储的公钥获取到 PublicKey 对象
     * @return
     * @throws Exception
     */
    private static PublicKey getPublicKey() throws Exception{
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
                new BASE64Decoder().decodeBuffer(CommonConstant.PUBLIC_KEY)
        );
        return KeyFactory.getInstance("RSA").generatePublic(keySpec);

    }
}
